<template>
  <div v-if="!hasPermission" class="no__permission--container">
    <n-result status="403" title="DATA LOCKED" description="当前无查看权限">
      <template #icon>
      <n-icon :size="64" color="#f0a020">
        <DocumentLockSharp/>
      </n-icon>
    </template>
    </n-result>
  </div>
  <n-layout v-else>
    <n-layout-header>
      <n-select style="width:240px" v-model:value="budgetSourceId" :options="eventsOptions"
        @update:value="getBudgetConstructor" />
      <n-button strong secondary type="info">
        新增预算
      </n-button>
    </n-layout-header>
    <n-layout-content>
      <n-table :single-line="false">
        <thead>
          <tr>
            <th align="center" width="30px">序号</th>
            <th align="center">预算年份</th>
            <th align="center">预算名称</th>
            <th align="center">预算类型</th>
            <th align="center">预算来源</th>
            <th align="center">预算金额</th>
            <th width="150px" align="center">剩余金额</th>
            <th align="center">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="8">
              <n-skeleton text /> <n-skeleton text style="width: 60%" />
            </td>
          </tr>
          <template v-else>
            <tr v-if="budgetList.length > 0" v-for="(item, index) in budgetList" :key="index">
              <td align="center" width="30px">{{ index + 1 }}</td>
              <td align="center" class="all__money__text">{{ item.budgetYear }}</td>
              <td align="center">{{ item.budgetName }}</td>
              <td align="center">{{ item.budgetType }}</td>
              <td align="center">{{ item.sourceEventName }}</td>
              <td align="center">
                <span class="all__money__text">￥{{ item.budgetMoney }}</span>
              </td>
              <td class="flex__td">
                <span class="left__money__text" @click="handleShowLog(item.moneyUseLog)">￥{{ item.leftMoeny }}</span>
                <n-tag size="small" :type="!item.leftMoeny ? 'error' : 'info'">{{ !item.leftMoeny ? '已用尽' : '待使用'
                }}</n-tag>
              </td>
              <th align="center">
                <n-button text @click="handleShowDrawer(item)">添加记录</n-button>
              </th>
            </tr>
            <tr v-else>
              <td align="center" colspan="8">
                暂无数据
              </td>
            </tr>
          </template>
        </tbody>
      </n-table>
    </n-layout-content>
  </n-layout>
  <!-- 模态弹窗 -->
  <n-modal v-model:show="showModal">
    <n-card style="width: 800px" title="预算使用历史记录" :bordered="false" size="huge" role="dialog" aria-modal="true">
      <n-table :single-line="false">
        <thead>
          <tr>
            <th align="center" width="30px">序号</th>
            <th align="center">填报人</th>
            <th align="center">填报日期</th>
            <th align="center">使用金额</th>
            <th align="center">使用原因</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="budgetLog.length > 0" v-for="(item, index) in budgetLog" :key="index">
            <td align="center" width="30px">{{ index + 1 }}</td>
            <td align="center" class="all__money__text">{{ item.reqPerson }}</td>
            <td align="center">{{ item.reqDate }}</td>
            <td align="center">￥{{ item.useMoney }}</td>
            <td align="center">{{ item.budgetDetail }}</td>
          </tr>
          <tr v-else>
            <td align="center" colspan="8">
              暂无数据
            </td>
          </tr>
        </tbody>
      </n-table>
      <template #footer>
        <n-button @click="showModal = false">关 闭</n-button>
      </template>
    </n-card>
  </n-modal>
  <!-- 抽屉组件 -->
  <n-drawer height="100%" v-model:show="showDrawer" placement="top">
    <n-drawer-content title="预算使用登记">
      <n-form ref="formRef" :rules="rules" :model="budgetUseForm">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="预算名称" path="budgetName">
            <n-input v-model:value="budgetUseForm.budgetName" disabled placeholder="请输入预算名称" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="预算编号" path="budgetId">
            <n-input-number style="width:100%" v-model:value="budgetUseForm.budgetId" disabled placeholder="请输入预算编号" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="填报人" path="reqPerson">
            <n-input v-model:value="budgetUseForm.reqPerson" disabled placeholder="请输入填报人" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="填报日期" path="reqDate">
            <n-date-picker style="width:100%" v-model:formatted-value="budgetUseForm.reqDate" value-format="yyyy-MM-dd"
              type="date" placeholder="请输入填报日期" clearable />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="使用金额" path="useMoney">
            <n-input-number :min="0" :max="budgetUseForm.leftMoney" v-model:value="budgetUseForm.useMoney"
              placeholder="请输入使用金额" />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="剩余金额">
            <n-input-number v-model:value="budgetUseForm.leftMoney" disabled />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="使用原因" path="budgetDetail">
            <n-input v-model:value="budgetUseForm.budgetDetail" maxlength="100" show-count type="textarea"
              placeholder="请输入使用原因" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
      <template #footer>
        <n-button style="margin-right: 1rem;" strong secondary type="info" @click="handleRegister">
          <span>登 记</span><span v-show="loading" style="margin-left:1rem"> <n-spin stroke="#fff" :size="12" /></span>
        </n-button>
        <n-button @click="showDrawer = false">关 闭</n-button>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<script setup lang='ts'>
import { getBudgetDetails, insetBudgetLog } from '@/api/backend/db';
import { getEvents } from '@/api/modules/admin'
import { getBudgetByEvent } from '@/api/modules/budget';
import { useUserStore } from '@/stores/user';
import { DocumentLockSharp } from '@vicons/ionicons5'
import { FormInst, useMessage, FormItemRule } from 'naive-ui';

interface BudgetRaw {
  budget_money: number
  budget_name: string
  budget_type: string
  budget_used: string
  budget_year: string
  change_time: string
  id: number
  source_event_id: number
  source_event_name: string
  update_person: string
  update_time: string
  use_person: string
  use_person_id: number
  use_status: string
  used_event_id: number
  used_event_name: string
}
interface BudgetVORaw {
  budgetMoney: number
  budgetName: string
  budgetType: string
  budgetYear: string
  sourceEventId: number
  sourceEventName: string
  status: string
  budgetId: number
}
interface BudgetVO extends BudgetVORaw {
  leftMoeny: number | null
  moneyUseLog: Budget[] | undefined
}

const hasPermission = computed(()=>{
  return userStore.userInfo.isadmin;
})
const message = useMessage();
const userStore = useUserStore();
const loading = ref(false);
const eventsOptions = reactive<any[]>([]);
const budgetList = reactive<BudgetVO[]>([]);
const budgetSourceId = ref<null | number>(null);
const budgetLog = reactive<Budget[]>([]);
const showModal = ref(false);
const showDrawer = ref(false);
const formRef = ref<null | FormInst>(null)
const budgetUseForm = reactive<BudgetDTO>({
  reqPerson: '',
  reqId: 0,
  budgetId: 0,
  budgetName: '',
  useMoney: 0,
  reqDate: '',
  budgetDetail: '',
  leftMoney: 0
});
const rules = {
  budgetName: {
    required: true,
    message: '请输入预算名称',
    trigger: ['input', 'blur']
  },
  reqPerson: {
    required: true,
    message: '请输入填报人',
    trigger: ['input', 'blur']
  },
  reqDate: {
    required: true,
    message: '请输入填报日期',
    trigger: ['input', 'blur']
  },
  useMoney: {
    required: true,
    message: '请输入使用预算金额',
    trigger: 'blur',
    validator(rule: FormItemRule, value: number) {
      console.log(rule);
      return value !== undefined && value !== null && value > 0;
    },
  },
  budgetDetail: {
    required: true,
    message: '请输入使用原因',
    trigger: ['input', 'blur']
  }
}
// 登记预算使用日志
const handleRegister = (e: MouseEvent) => {
  e.preventDefault()
  formRef.value?.validate((errors) => {
    if (!errors) {
      uploadForm();
    }
    else {
      message.error('请完整输入表单内容！')
    }
  })
}
const uploadForm = async () => {
  try {
    loading.value = true;
    const response = await insetBudgetLog(budgetUseForm);
    if (response.code !== 200) throw new Error(response.message);
    showDrawer.value = false;
    getBudgetConstructor(budgetSourceId.value as number);
    message.success('更新成功！');
    Object.assign(budgetUseForm, {
      reqPerson: '',
      reqId: 0,
      budgetId: 0,
      budgetName: '',
      useMoney: 0,
      reqDate: '2025-01-01',
      budgetDetail: '',
      leftMoney: 0
    })
  } catch (error) {
    message.error(error instanceof Error ? error.message : String(error));
  }

}
// 初始化
const initData = async () => {
  try {
    loading.value = true;
    const eventRes = await getEvents() as any[];
    eventRes.forEach(event => {
      eventsOptions.push({
        value: event.id,
        label: event.name
      })
    })
    budgetSourceId.value = eventRes[0].id as number;
    getBudgetConstructor(budgetSourceId.value);
  } catch (error) {
    throw new Error(error instanceof Error ? error.message : String(error))
  }
}
const getBudgetConstructor = async (id: number) => {
  try {
    loading.value = true;
    budgetList.length = 0;
    const response = await getBudgetByEvent(id) as symbolResponse;
    const budgetListRaw: BudgetVORaw[] = (response?.data ?? []).map((raw: BudgetRaw) => {
      return {
        budgetMoney: raw.budget_money,
        budgetName: raw.budget_name,
        budgetType: raw.budget_type,
        budgetYear: raw.budget_year,
        sourceEventId: raw.source_event_id,
        sourceEventName: raw.source_event_name,
        status: raw.use_status,
        budgetId: raw.id
      }
    })
    const { code, message, data } = await getBudgetDetails();
    if (code !== 200) throw new Error(message);
    if (response && response.data && Array.isArray(response.data)) {
      budgetListRaw.forEach((budget: BudgetVORaw) => {
        const sourceBudgetList = (data ?? []).filter(child => child.budgetId === budget.budgetId);
        const hasUseMoeny = sourceBudgetList.reduce((pre, next) => pre + next.useMoney, 0);
        budgetList.push({
          ...budget,
          leftMoeny: budget.budgetMoney - hasUseMoeny,
          moneyUseLog: sourceBudgetList ?? []
        })
      });
    }
  } catch (error) {
    message.error(error instanceof Error ? error.message : String(error));
  } finally {
    loading.value = false;
  }
}
// 展示log
const handleShowLog = (moneyUseLog: Budget[] | undefined) => {
  budgetLog.length = 0;
  (moneyUseLog ?? []).forEach(item => {
    budgetLog.push(item);
  });
  showModal.value = true;
}
// 展示新预算
const handleShowDrawer = (item: BudgetVO) => {
  showDrawer.value = true;
  Object.assign(budgetUseForm, {
    reqPerson: userStore.userInfo.chinaname,
    reqId: userStore.userInfo.id,
    budgetId: item.budgetId,
    budgetName: item.budgetName,
    leftMoney: item.leftMoeny,
    reqDate: '2025-01-01'
  })
}
initData();
</script>
<style scoped lang='scss'>
.n-layout-header {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 1.2rem;
}
.no__permission--container{
  height:calc(100vh - 54px);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}
.n-layout-content {
  height: calc(100vh - 54px - 50px);
  overflow-y: auto;
  padding: 0 1.2rem;

  .all__money__text {
    color: #4090EF;
  }

  .flex__td {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 150px;

    .left__money__text {
      text-decoration: underline;
      text-underline-offset: 0.2rem;
      color: #F40;
      cursor: pointer;
      margin-right: 0.5rem;
    }
  }
}
</style>